/**
 * @file 支付看板
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-01-19
 */
import React, {useState, useEffect} from 'react';
import {Space, Card, Input, Row, Col} from 'antd';

import moment from 'moment';

import {
    getPayBoardResult,
    fetchSearchFormOptions,
    fetchDetail,
    downLoad
} from '~/service/payboard';

import {getFirstAndLastTimestamp, YESTERDAY} from '~/utils/date';
import {numberHandle, parsePercent} from '~/utils/number';
import {convertChartListToMap} from '../utils/convert';

import CommonSearchBar from '../common/CommonSearchBar';
import CommonCard from '../common/CommonCard';
import DetailModal from '../common/DetailModal';
import EchartsPieCard from '../common/EchartsPieCard';
import EchartsLineCard from '../common/EchartsLineCard';
import CommonTitle from '../common/Title';
import {formatTooltip} from '../utils/formatTooltip';
import PayBoardTextCard from './components/payBoardTextCard';

import {searchForm, dashBoardList, getDimensionId, pageId, META} from './config';

import './index.styl';

const {TextArea} = Input;

const initialValues = {
    startClassTime: getFirstAndLastTimestamp({format: 'YYYY-MM-DD'})
};


const PayBoard = props => {
    const [loading, setLoading] = useState(false);
    const [loading1, setLoading1] = useState(false);
    const [loading2, setLoading2] = useState(false);
    const [loading3, setLoading3] = useState(false);
    const [loading4, setLoading4] = useState(false);
    const [loading5, setLoading5] = useState(false);
    const [loading6, setLoading6] = useState(false);
    const [loading7, setLoading7] = useState(false);
    const [loading8, setLoading8] = useState(false);
    const [result, setResult] = useState({});
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    const {
        orderPaidThisMonthPartOne = {},
        orderPaidThisMonthPartTwo = {},
        orderPaidThisMonthPartThree = {},
        orderPaidThisMonthPartFour = {},
        orderPaidThisMonthPartFive = {},
        orderPaidThisMonthPartSix = {}
    } = result;

    const {newOrders, perCapitaCost} = orderPaidThisMonthPartOne;
    const {compositeUnit: compositeTwo} = orderPaidThisMonthPartTwo;
    const {pieUnit: pieThree} = orderPaidThisMonthPartThree;
    const {compositeUnit: compositeFour, barUnit: barFour} = orderPaidThisMonthPartFour;
    const {pieUnit: pieFive} = orderPaidThisMonthPartFive;
    const {pieUnit: pieSix, compositeUnit: compositeSix} = orderPaidThisMonthPartSix;

    const resultPartOneNewOrders = convertChartListToMap(newOrders);
    const resultPartOnePerCapitaCost = convertChartListToMap(perCapitaCost);
    const resultPartTwoComposite = convertChartListToMap(compositeTwo);
    const resultPartThreePie = convertChartListToMap(pieThree);
    const resultPartFourComposite = convertChartListToMap(compositeFour);
    const resultPartFourBar = convertChartListToMap(barFour);
    const resultPartFivePie = convertChartListToMap(pieFive);
    const resultPartSixPie = convertChartListToMap(pieSix);
    const resultPartSixComposite = convertChartListToMap(compositeSix);

    const {
        [META.PART_ONE_CARD_ONE]: partOneCardOne,
        [META.PART_ONE_SIMPLE_EXCEL_ONE]: partOneExcelOne
    } = resultPartOneNewOrders;

    const {
        [META.PART_ONE_CARD_TWO]: partOneCardTwo,
        [META.PART_ONE_SIMPLE_EXCEL_TWO]: partOneExcelTwo,
        [META.PART_ONE_CARD_THREE]: partOneCardThree,
        [META.PART_ONE_SIMPLE_EXCEL_THREE]: partOneExcelThree,
    } = resultPartOnePerCapitaCost;

    const {
        [META.PART_TWO_COMPOSITE_ONE]: partTwoCompositeOne,
    } = resultPartTwoComposite;

    const {
        [META.PART_THREE_PIE_ONE]: partThreePieOne
    } = resultPartThreePie;

    const {
        [META.PART_FOUR_COMPOSITE_ONE]: partFourCompositeOne
    } = resultPartFourComposite;

    const {
        [META.PART_FOUR_BAR_ONE]: partFourBarOne
    } = resultPartFourBar;

    const {
        [META.PART_FIVE_PIE_ONE]: partFivePieOne,
        [META.PART_FIVE_PIE_TWO]: partFivePieTwo,
        [META.PART_FIVE_PIE_THREE]: partFivePieThree,
    } = resultPartFivePie;

    const {
        [META.PART_SIX_COMPOSITE_ONE]: partSixCompositeOne,
        [META.PART_SIX_COMPOSITE_TWO]: partSixCompositeTwo,
        [META.PART_SIX_COMPOSITE_THREE]: partSixCompositeThree,
    } = resultPartSixComposite;

    const {
        [META.PART_SIX_PIE_ONE]: partSixPieOne
    } = resultPartSixPie;

    // 获取全局数据
    const getData = (params = searchFormValues) => {
        const {loadingFn = setLoading} = params;
        loadingFn(true);

        const {startClassTime} = params;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        params.beginTime = [beginRangeTime, endRangeTime];
        params.dashBoardList = dashBoardList;

        getPayBoardResult(params)
            .then(res => {
                const {
                    data
                } = res;

                setResult(data);
            })
            .finally(() => {
                loadingFn(false);
            });
    };

    const handleDetail = unit => {
        const {startClassTime} = searchFormValues;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            dashBoardList
        };
        params.beginTime = [beginRangeTime, endRangeTime];

        setDetailModalVisible(true);
        fetchDetail(params)
            .then(res => {
                setDetailData(res.data || {});
            });
    };

    const handleDownload = unit => {
        const {startClassTime} = searchFormValues;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            dashBoardList
        };
        params.beginTime = [beginRangeTime, endRangeTime];
        const excelName = unit.unitName;

        downLoad({params, excelName});
    };

    const handleBack = loadingFn => async params => {
        console.log('返回', params);
        const {unitId, unitName} = params;
        // 所有下钻取消
        setDrilingList([]);

        try {
            await getData({...searchFormValues, loadingFn});
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        }
        catch {}
    };

    const handleDrilling = loadingFn => async params => {
        console.log('下钻', params);
        const {unitId, unitName, info, dimension = {}} = params;

        const driling = {
            unitId,
            unitName,
            value: info.name,
            ...dimension
        };

        setDrilingList([driling]);

        try {
            await getData({...searchFormValues, drilingList: [driling], loadingFn});
            // 搜索接口调用成功后level + 1
            setDrilingLevel({unitId, level: 1});
        }
        catch {}
    };

    useEffect(() => {
        getData({...initialValues, loadingFn: setLoading1});
    }, []);

    // 表单确定
    const handleOk = fieldsValue => {
        setSearchFormValues(fieldsValue);
        setDrilingLevel(null);
        setDrilingList([]);
        getData({...fieldsValue, loadingFn: setLoading1});
    };

    // 表单重置
    const handleReset = e => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList([]);
        getData({...initialValues, loadingFn: setLoading1});
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        // setSearchFormValues({...searchFormValues, ...itemKeyValue});
        console.log('handleItemChange', itemKeyValue);
    };

    // 请求单个表单配置项
    const handleFetchOptions = (
        {key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}
    ) => {
        let permissions = searchForm.map(item => {
            if (item.key === 'startClassTime') {
                const [begin, end] = fieldsValue[item.key] || [];
                const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
                const endRangeTime = end && moment(end).format('YYYY-MM-DD');
                const filterItems = [beginRangeTime, endRangeTime];
                const dimensionId = getDimensionId(0, 'beginTime');

                return (
                    {
                        dimensionId,
                        dimensionName: 'beginTime',
                        filterItems
                    }
                );
            }
            return (
                {
                    dimensionId: getDimensionId(0, item.key),
                    dimensionName: item.key,
                    filterItems: fieldsValue[item.key]
                }
            );
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: key,
            searchKey,
            permissions,
            dashBoardList,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    return (
        <div className="pay-board-conatiner">
            <CommonTitle
                title="本月支付订单"
                time={YESTERDAY}
                containerStyle={{justifyContent: 'space-between'}}
            />
            <div className="pay-board-content">
                <Space direction="vertical" style={{width: '100%'}}>
                    <Card style={{width: '100%', marginTop: 24}}>
                        <CommonSearchBar
                            loading={loading1}
                            noCache
                            config={searchForm}
                            initialValues={initialValues}
                            onOk={handleOk}
                            onReset={handleReset}
                            onItemChange={handleItemChange}
                            onfetchOptions={handleFetchOptions}
                            selectOptions={selectOptions}
                        />
                    </Card>
                    <Card style={{width: '100%'}}>
                        <TextArea
                            className="pay-board-text-area"
                            rows={3}
                            value={result?.orderPaidThisMonthPartOne?.textList[0].textContent}
                            bordered={false}
                            readOnly
                        />
                        <div className="part-one">
                            <Row>
                                <Col span={8}>
                                    <PayBoardTextCard
                                        unitId={META.PART_ONE_SIMPLE_EXCEL_ONE}
                                        unitName={partOneCardOne?.unitName ?? ''}
                                        onDownload={handleDownload}
                                        onDetail={handleDetail}
                                        loading={loading1}
                                        data={partOneCardOne}
                                        excelData={partOneExcelOne}
                                    />
                                </Col>
                                <Col span={8}>
                                    <PayBoardTextCard
                                        unitId={META.PART_ONE_SIMPLE_EXCEL_TWO}
                                        unitName={partOneCardTwo?.unitName ?? ''}
                                        onDownload={handleDownload}
                                        onDetail={handleDetail}
                                        loading={loading1}
                                        data={partOneCardTwo}
                                        excelData={partOneExcelTwo}
                                    />
                                </Col>
                                <Col span={8}>
                                    <PayBoardTextCard
                                        unitId={META.PART_ONE_SIMPLE_EXCEL_THREE}
                                        unitName={partOneCardThree?.unitName ?? ''}
                                        onDownload={handleDownload}
                                        onDetail={handleDetail}
                                        loading={loading1}
                                        data={partOneCardThree}
                                        excelData={partOneExcelThree}
                                    />
                                </Col>
                            </Row>
                        </div>
                        <div className="part-two-three">
                            <Row>
                                <EchartsLineCard
                                    id={META.PART_TWO_COMPOSITE_ONE}
                                    data={partTwoCompositeOne}
                                    loading={loading || loading1 || loading2}
                                    span={12}
                                    title={partTwoCompositeOne?.unitName ?? ''}
                                    onBack={handleBack(setLoading2)}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling(setLoading2)}
                                    drilingLevel={drilingLevel}
                                    grid={{left: '8%', right: '8%', bottom: 100}}
                                    // label={{
                                    //     line: params => `${numberHandle(params.data.value, 2)}`,
                                    //     bar: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    tooltip={params => formatTooltip(params)}
                                    yAxisIndex={1}
                                    key={META.PART_TWO_COMPOSITE_ONE}
                                />
                                <EchartsPieCard
                                    id={META.PART_THREE_PIE_ONE}
                                    key={META.PART_THREE_PIE_ONE}
                                    span={12}
                                    title={partThreePieOne?.unitName ?? ''}
                                    loading={loading || loading1 || loading3}
                                    onDetail={handleDetail}
                                    onDownload={handleDownload}
                                    onDrilling={handleDrilling(setLoading3)}
                                    pieUnit={partThreePieOne}
                                    onBack={handleBack(setLoading3)}
                                    drilingLevel={drilingLevel}
                                    labelCallback={params => {
                                        if (params.data.proportion < 0.05) {
                                            return;
                                        }
                                        return `${params.data.name}: ${parsePercent(params.data.proportion)}`;
                                    }}
                                    tooltipCallback={params =>
                                        `${params.data.name}: ${numberHandle(params.data.value, 2)}<br/>
                                        占比: ${parsePercent(params.data.proportion)}
                                        `
                                    }
                                />
                            </Row>
                        </div>
                        <div className="part-four">
                            <Row>
                                <EchartsLineCard
                                    id={META.PART_FOUR_COMPOSITE_ONE}
                                    key={META.PART_FOUR_COMPOSITE_ONE}
                                    data={partFourCompositeOne}
                                    loading={loading || loading1 || loading4}
                                    span={24}
                                    title={partFourCompositeOne?.unitName ?? ''}
                                    onBack={handleBack(setLoading4)}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling(setLoading4)}
                                    drilingLevel={drilingLevel}
                                    grid={{left: '8%', right: '5%', bottom: 100}}
                                    dataZoomEnd={100}
                                    // label={{
                                    //     line: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    tooltip={params => formatTooltip(params)}
                                    stack="总量"
                                    rotate={30}
                                />
                            </Row>
                        </div>
                        <div className="part-five">
                            <Row>
                                <EchartsLineCard
                                    id={META.PART_FOUR_BAR_ONE}
                                    key={META.PART_FOUR_BAR_ONE}
                                    data={partFourBarOne}
                                    loading={loading || loading1 || loading5}
                                    span={12}
                                    title={partFourBarOne?.unitName ?? ''}
                                    onBack={handleBack(setLoading5)}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling(setLoading5)}
                                    drilingLevel={drilingLevel}
                                    grid={{left: '8%', right: '5%', bottom: 100}}
                                    // label={{
                                    //     bar: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    tooltip={params => formatTooltip(params)}
                                />
                                <EchartsPieCard
                                    id={META.PART_FIVE_PIE_ONE}
                                    key={META.PART_FIVE_PIE_ONE}
                                    span={12}
                                    title={partFivePieOne?.unitName ?? ''}
                                    loading={loading || loading1 || loading6}
                                    onDetail={handleDetail}
                                    onDownload={handleDownload}
                                    onDrilling={handleDrilling(setLoading6)}
                                    pieUnit={partFivePieOne}
                                    onBack={handleBack(setLoading6)}
                                    drilingLevel={drilingLevel}
                                    tooltipCallback={params =>
                                        `${params.data.name}: ${numberHandle(params.data.value, 2)}<br/>
                                        占比: ${parsePercent(params.data.proportion)}
                                        `
                                    }
                                    labelCallback={params => {
                                        if (params.data.proportion < 0.05) {
                                            return;
                                        }
                                        return `${params.data.name} \n ${parsePercent(params.data.proportion)}`;
                                    }}
                                />
                            </Row>
                        </div>
                        <div className="part-six">
                            <Row>
                                <EchartsPieCard
                                    id={META.PART_SIX_PIE_ONE}
                                    key={META.PART_SIX_PIE_ONE}
                                    span={12}
                                    title={partSixPieOne?.unitName ?? ''}
                                    loading={loading || loading1 || loading7}
                                    onDetail={handleDetail}
                                    onDownload={handleDownload}
                                    onDrilling={handleDrilling(setLoading7)}
                                    pieUnit={partSixPieOne}
                                    onBack={handleBack(setLoading7)}
                                    drilingLevel={drilingLevel}
                                    tooltipCallback={params =>
                                        `${params.data.name}: ${numberHandle(params.data.value, 2)}<br/>
                                        占比: ${parsePercent(params.data.proportion)}
                                        `
                                    }
                                    labelCallback={params => {
                                        if (params.data.proportion < 0.05) {
                                            return;
                                        }
                                        return `${params.data.name} \n ${parsePercent(params.data.proportion)}`;
                                    }}
                                />
                                <EchartsLineCard
                                    id={META.PART_SIX_COMPOSITE_ONE}
                                    key={META.PART_SIX_COMPOSITE_ONE}
                                    data={partSixCompositeOne}
                                    loading={loading || loading1 || loading8}
                                    span={12}
                                    title={partSixCompositeOne?.unitName ?? ''}
                                    onBack={handleBack(setLoading8)}
                                    onDownload={handleDownload}
                                    onDetail={handleDetail}
                                    onDrilling={handleDrilling(setLoading8)}
                                    drilingLevel={drilingLevel}
                                    grid={{left: '12%', right: '2%', bottom: 100}}
                                    dataZoomEnd={100}
                                    // label={{
                                    //     bar: params => `${numberHandle(params.data.value, 2)}`
                                    // }}
                                    tooltip={params => formatTooltip(params)}
                                    rotate={30}
                                />
                            </Row>
                        </div>
                    </Card>
                </Space>
            </div>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default PayBoard;
